package com.voxel.sense.infomsg.module.task.execution.report.details;

import android.text.TextUtils;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.TaskReportElementBean;
import com.voxel.sense.infomsg.data.bean.TaskReportHeadBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.request.UpReportEntity;
import cyy.example.com.facotry.model.api.response.ReportEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.TaskNetHelper;

/**
 * @author ChenYiYao
 * @date 2018/5/14
 * des :
 */
public class DetailsTaskReportPresenter extends BasePresenter<TaskReportContract.View>
        implements TaskReportContract.Presenter, DataSource.Callback<BaseEntity> {

    private List<TaskReportHeadBean> mRecyclerBeans;
    private String mFormName;//表格名称
    private String mFormCode;
    boolean isUpReport = false;
    private int mStatus;

    public DetailsTaskReportPresenter(TaskReportContract.View view) {
        super(view);
    }

    @Override
    public void doLoadRePort(String formCode) {
        TaskNetHelper.getTaskReport(formCode, this);
    }

    @Override
    public void doLoadExistRePort(String formCode, String tastNumb, int status) {
        mStatus = status;
        TaskNetHelper.getReportAndValue(tastNumb, formCode, this);
    }


    @Override
    public void doUpLoadReport(List list, String TaskNumb, int status) {
        //由于adpter中引用的数据源与mRecyclerBeans相同，这里可直接用该对象获取到对应值
        if (!isUpReport && mRecyclerBeans != null && mRecyclerBeans.size() > 0) {
            boolean isHaveValue = false;
            //创建上传表格的实体
            UpReportEntity upEntity = new UpReportEntity();
            List<ReportEntity.FormElementListBean> formElementList = new ArrayList<>();
            String param1 = "";

            for (TaskReportHeadBean bean : mRecyclerBeans) {
                List<TaskReportElementBean> subItems = bean.getSubItems();
                for (TaskReportElementBean element : subItems) {
                    ReportEntity.FormElementListBean eleData = element.getBean();
                    ReportEntity.FormElementListBean.ValueGroupBean valueGroup = eleData.getValueGroup();
                    if (!isHaveValue && (!TextUtils.isEmpty(valueGroup.getRemark()) || !TextUtils.isEmpty(valueGroup.getResultRecord())
                            || !TextUtils.isEmpty(valueGroup.getSelectValue()))) {
                        //将任务字段及param1是否备注字段赋值
                        param1 = element.getParam1();
                        upEntity.setTaskNumber(TaskNumb);
                        upEntity.setFormDetailsVo(new ArrayList<>());
                        isHaveValue = true;
                    }
                    formElementList.add(eleData);
                }
            }

            if (isHaveValue) {
                /**
                 * 这里设置diaolog不可取消，为了防止在上传过程中退出activity返回列表界面，再次从列表界面进入
                 * 这时有可能上个修改请求成功，但之前的状态并没有改变，依然调用首次上传的接口。
                 */
                mView.showLoading("", false);
                ReportEntity reportEntity = new ReportEntity(mFormCode, mFormName, param1, formElementList);
                upEntity.getFormDetailsVo().add(reportEntity);
                if (status == TaskReportContract.UP_REPORT) {
                    TaskNetHelper.UpLoadReport(upEntity, this);
                } else {
                    TaskNetHelper.UpDataReport(upEntity, this);
                }

            } else {
                mView.showSnackbar("不能提交空内容，请填写后提交");
            }
        }
    }


    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        if (mView == null) {
            return;
        }
        if (reqId == RequestIdFactory.GET_TASK_REPORT) {
            //获取空报表
            loadEmptyReportSuccess(data);
        } else if (reqId == RequestIdFactory.GET_REPORT_AND_VALUE) {
            //获取有值的报表
            loadReportSuccess(data);
        } else if (reqId == RequestIdFactory.UP_LOAD_REPORT || reqId == RequestIdFactory.UP_DATA_REPORT) {
            isUpReport = false;
            mView.dimissLoading();
            if (data.isSuccess()) {
                mView.onUpReportSuccess();
                //发送上传表格成功的通知
                EventBus.getDefault().post(new EventEntity(EventBusConstants.UP_REPORT_SUCCESS, mFormCode));
            } else {
                upReportFailure();
            }
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }

        if (reqId == RequestIdFactory.GET_TASK_REPORT || reqId == RequestIdFactory.GET_REPORT_AND_VALUE) {
            mView.onAdapterDataChanged();
        } else if (reqId == RequestIdFactory.UP_LOAD_REPORT || reqId == RequestIdFactory.UP_DATA_REPORT) {
            isUpReport = false;
            mView.dimissLoading();
            upReportFailure();
        }
    }

    private void upReportFailure() {
        if (!NetworkUtils.isConnected()) {
            mView.showSnackbar(Factory.app().getString(R.string.network_unavailable));
        } else {
            mView.showSnackbar("表格上传失败");
        }
    }

    private void loadEmptyReportSuccess(BaseEntity data) {
        if (data.isSuccess() && data.getData() != null) {
            handleReportData((ReportEntity) data.getData());
        } else {
            //获取失败
        }
        mView.onAdapterDataChanged();
    }

    private void loadReportSuccess(BaseEntity data) {
        if (data.isSuccess() && data.getData() != null) {
            List<ReportEntity> entityList = (List<ReportEntity>) data.getData();
            if (!ListUtil.isEmpty(entityList)) {
                ReportEntity reportEntity = entityList.get(0);
                handleReportData(reportEntity);
            }
        }
        mView.onAdapterDataChanged();
    }

    private void handleReportData(ReportEntity data) {
        if (data.getFormElementList() == null || data.getFormElementList().size() < 1) {
            mView.onAdapterDataChanged();
            return;
        }

        //组装recycview列表的数据
        mFormName = data.getFormName();
        mFormCode = data.getFormCode();
        String param1 = data.getParam1();
        List<ReportEntity.FormElementListBean> formElementList = data.getFormElementList();
        //recyc的数据
        mRecyclerBeans = new ArrayList<>();
        //一级item的数据
        TaskReportHeadBean headBean = new TaskReportHeadBean();

        for (ReportEntity.FormElementListBean reportbean : formElementList) {
            //先判断该二级项，是不是在同一个一级项下。相同则添加，不同则new新的一级项。
            //获取item是否可编辑的状态
            boolean flag = (TaskReportContract.LOOK_REPORT == mStatus ? false : true);
            if (!TextUtils.isEmpty(reportbean.getPreEleCode()) &&
                    reportbean.getPreEleCode().equals(headBean.getCode())) {
                headBean.addSubItem(new TaskReportElementBean(reportbean, param1,flag));
            } else {
                headBean = new TaskReportHeadBean();
                headBean.setCode(reportbean.getPreEleCode());
                headBean.setDesc(reportbean.getPreEleContent());
                headBean.addSubItem(new TaskReportElementBean(reportbean, param1, flag));
                mRecyclerBeans.add(headBean);
            }
        }
        mView.dimissLoading();
        mView.onRefreshData(mRecyclerBeans);
    }


}
